// 位置和天气相关的API服务

// 统一天气API响应接口
interface WeatherApiResponse {
  precipitation: number
  temperature: number
  pressure: number
  humidity: number
  windDirection: string
  windDirectionDegree: number
  windSpeed: number
  windScale: string
  feelst: number
  code: number
  place: string
  weather1: string
  weather2: string
  weather1img: string
  weather2img: string
  uptime: string
  jieqi: string
}

// 位置信息接口
interface LocationResponse {
  country: string
  region: string
  city: string
  lat: number
  lon: number
  timezone: string
}

// 获取位置和天气信息（使用统一的中文API）
export const getLocationAndWeather = async () => {
  try {
    // 使用统一的中文天气API
    const response = await fetch('https://cn.apihz.cn/api/tianqi/tqybip.php?id=10006921&key=af5ec486ea8982fa43052489d8778b78')
    
    if (!response.ok) {
      throw new Error('获取位置和天气信息失败')
    }
    
    const data: WeatherApiResponse = await response.json()
    
    if (data.code !== 200) {
      throw new Error('API返回错误')
    }
    
    // 解析位置信息
    const placeParts = data.place.split(', ')
    const country = placeParts[2] || ''
    const region = placeParts[1] || ''
    const city = placeParts[0] || ''
    
    // 格式化地址
    const address = data.place
    
    // 格式化天气信息
    const weather = `${data.weather1} ${Math.round(data.temperature)}°C`
    
    // 构建位置对象（用于兼容性）
    const location: LocationResponse = {
      country,
      region,
      city,
      lat: 0, // 这个API不提供经纬度
      lon: 0,
      timezone: ''
    }
    
    return {
      address,
      weather,
      location,
      // 额外提供详细的天气信息
      weatherDetail: {
        temperature: data.temperature,
        feelsLike: data.feelst,
        humidity: data.humidity,
        windDirection: data.windDirection,
        windSpeed: data.windSpeed,
        windScale: data.windScale,
        pressure: data.pressure,
        precipitation: data.precipitation,
        weatherDesc: data.weather1,
        updateTime: data.uptime
      }
    }
  } catch (error) {
    console.error('获取位置和天气信息失败:', error)
    throw error
  }
}

// 为了兼容性，保留这些函数但使用新的API
export const getCurrentLocation = async (): Promise<LocationResponse> => {
  try {
    const result = await getLocationAndWeather()
    return result.location
  } catch (error) {
    console.error('获取位置信息失败:', error)
    throw error
  }
}

export const getWeatherInfo = async (lat: number, lon: number) => {
  try {
    const result = await getLocationAndWeather()
    return {
      weather: [{
        main: result.weatherDetail.weatherDesc,
        description: result.weatherDetail.weatherDesc,
        icon: ''
      }],
      main: {
        temp: result.weatherDetail.temperature,
        feels_like: result.weatherDetail.feelsLike,
        humidity: result.weatherDetail.humidity,
        pressure: result.weatherDetail.pressure
      },
      name: result.location.city
    }
  } catch (error) {
    console.error('获取天气信息失败:', error)
    throw error
  }
}

// 格式化函数保持不变，但使用新的数据结构
export const formatAddress = (location: LocationResponse): string => {
  const parts = []
  if (location.city) parts.push(location.city)
  if (location.region) parts.push(location.region)
  if (location.country) parts.push(location.country)
  
  return parts.join(', ')
}

export const formatWeather = (weatherData: any): string => {
  // 直接使用API返回的格式化数据
  if (weatherData.weatherDetail) {
    return `${weatherData.weatherDetail.weatherDesc} ${Math.round(weatherData.weatherDetail.temperature)}°C`
  }
  
  // 兼容旧格式
  const weatherMain = weatherData.weather?.[0]?.main || ''
  const weatherDesc = weatherData.weather?.[0]?.description || ''
  const temp = Math.round(weatherData.main?.temp || 0)
  
  return `${weatherDesc} ${temp}°C`
}
